//
//  ST_PeculiarityGroupViewController.swift
//  btvideo
//
//  Created by mac on 2020/5/26.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwifterSwift
import HandyJSON
import SnapKit
import SwiftyUserDefaults
import NIMSDK
import SwiftyJSON
import MJRefresh
import SwiftyAttributes


weak var CURRENT_PLAYING_GROUPHEADER_VIEW:ST_PeculiarityGroupHeaderView?

/**
 特质详情 组
 */
class ST_PeculiarityGroupViewController: UIViewController {
    
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }
    
    convenience init(accid:String,groupId:String,peculiarity_id:String,firstPhotoSize:CGSize,remark:String) {
        
        self.init(nibName: nil, bundle: nil)
        
        self.accid = accid
        
        self.groupId = groupId
        
        self.peculiarity_id = peculiarity_id
        
        self.headerModel.accid = accid
        
        self.headerModel.frameModel = ST_PeculiarityGroupHeaderFrameModel.init(accid: accid, remark: remark, albumSize: firstPhotoSize)
        
        
        self.header_height = self.headerModel.frameModel.header_height
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        self.headerView.playerStatus(isMute: true)
    }
    
    deinit {
        print("内存释放问题----0")
    }
    
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
         
        
        view.backgroundColor = Color.clear
        
        let bottomEdge : CGFloat = iPhoneXSeries ? 0 : -30
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.init(top: statusBarHeight, left: 0, bottom: bottomEdge, right: 0))
        }
        tableView.cornerRadius = 30
        
        view.addSubview(back_btn)
        back_btn.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.top.equalToSuperview().offset(statusBarHeight+7)
            make.width.height.equalTo(30)
        }
        
        
        fetch_remote_data_set()
        
        
            
        view.addSubview(more_action_btn)
        more_action_btn.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-15)
            make.top.equalToSuperview().offset(statusBarHeight+7)
            make.width.height.equalTo(30)
        }
        
        
        
        /*
        view.addSubview(bottom_input_action_view)
        bottom_input_action_view.snp.makeConstraints { (make) in
            make.height.equalTo(ST_PecGroupBottomView.height)
            make.bottom.left.right.equalToSuperview()
        }
        */
        
        view.addSubview(comment_input_mask_view)
        comment_input_mask_view.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        view.addSubview(comment_input_bar)
        comment_input_bar.snp.makeConstraints { (make) in
            make.height.equalTo(ST_CommentInputBar.height)
            make.bottom.left.right.equalToSuperview()
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(refresh_love_botton), name: Notification.Name.pairs_prop_updated, object: nil)
        
        
        self.footerView.modify_height_closure = {[weak self] height in
            
            self?.footerView.frame = CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: ScreenWidth, height: height))
            
            self?.tableView.tableFooterView = self?.footerView
        }
        
    }
    
    //    MARK: - Set Up Data
    @objc func fetch_remote_data_set() {
        
        request_recommend_data()
        
        JVrequest(PH.peculiarityGroupDetailApi,parameters: ["target_accid":accid,"feature_id":self.peculiarity_id,"group_id":self.groupId],success: { (json) in
            
            print("特质分组 数据集:",json)
            
            self.hidden_indeterminate_h_u_d()
            
            let data = json["data"]
            
            self.headerModel = ST_PeculiarityGroupHeaderViewModel.init(user: data["user_info"], list: data["content"].arrayValue)
            
            self.headerModel.peculiarityName = data["feature_name"].stringValue
            
            self.headerModel.peculiarityType = data["feature_type"].intValue
            
            self.headerModel.accid = self.accid
            
            self.headerModel.group_id = self.groupId
            
            self.headerModel.peculiarity_id = self.peculiarity_id
            
            self.header_height = self.headerModel.frameModel.header_height
            
            self.headerView.bind_model(self.headerModel)
            
            self.headerView.playerStatus(isMute: false)
            
            self.layout_operation_btns()
            
            CURRENT_PLAYING_GROUPHEADER_VIEW = self.headerView
            
            if let m  = ST_PecGroupCommentsCellModel.deserialize(from: data["comment"].rawString() ?? ""){
                self.commentsViewModel = m
                
//                无数据测试 0  ,pass
//                一条数据测试 1  ,pass
//                一条数据测试 2  ,pass
                
                self.commentsViewModel.groupId = self.groupId.int ?? 0
                
                self.commentsViewModel.userId = self.accid
                
                self.commentsViewModel.peculiarity_id = self.peculiarity_id
                
                self.commentsViewModel.type = data["is_emoji_feature"].boolValue ? 2 : 1
                
                self.comment_input_bar.onlyInputEmoji = data["is_emoji_feature"].boolValue
                
                self.commentsViewModel.setUpFrame()
            }
            
            
            self.hidden_indeterminate_h_u_d()
            
            self.tableView.reloadData {
                
                self.tableView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: {[weak self] in
                    
                    self?.load_recommend_data()
                })
            }
            
            
            
            
        }) { (code, error) in
            
//            self.hidden_indeterminate_h_u_d()
            print("当前错误❌:",error)
            self.toast(text: error)
            
        }
        
    }
    
    fileprivate var recommendData = [ST_TraitOfOperatCellModel]()
    
    fileprivate var loadingRecommend:Bool?{
        didSet{
            self.load_recommend_data()
        }
    }
    
    fileprivate func load_recommend_data(){
        
//        加载完成
        if let f = loadingRecommend,f == false{
            
            self.footerView.data_array = recommendData

            self.tableView.mj_footer = nil
        }
    }
    
    /**请求 推荐数据*/
    fileprivate func request_recommend_data(){
        
        
        loadingRecommend = true
        
        let param = ["page":1,"feature_id":peculiarity_id,"target_accid":accid,"size":20] as [String : Any]
        
        print("推荐特质Request：-",Date())
        
        JVrequest(PH.RecommendPeculiarityApi,parameters: param, success: { (json) in
            
            print("推荐特质Response：-",Date())
//            print("推荐特质:",json)
            
            let list = json["data"].arrayValue
            
            
            let aArray = list.map { (itemJson) -> ST_TraitOfOperatCellModel in
                let m = ST_TraitOfOperatCellModel.init(json: itemJson)
                m.create_view_model_set(maxContentHeight: ST_ShowTraitCell.two_line_max_height)
                return m
            }
            
            self.recommendData = aArray
            
            self.loadingRecommend = false
            
        }) { (code, err) in
            
            self.loadingRecommend = false
        }
        
    }
    
    //    MARK: - Data Array
    lazy var headerModel:ST_PeculiarityGroupHeaderViewModel = {
       let control = ST_PeculiarityGroupHeaderViewModel()
        return control
    }()
    
    
    fileprivate lazy var commentsViewModel = ST_PecGroupCommentsCellModel()
    
    /**
     外部传递
     */
    fileprivate var accid = ""

    fileprivate var groupId = ""
    
    fileprivate var peculiarity_id = ""
    
    //    MARK: - properties
    fileprivate lazy var back_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImageForAllStates(ST_ImageUtils.imageName("详情_icon_返回")!)
        control.addTarget(self, action: #selector(back_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var more_action_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImageForAllStates(ST_ImageUtils.imageName("详情_icon_更多操作")!)
        control.addTarget(self, action: #selector(actions_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    
    
    lazy var tableView:UITableView = {
        
        let control = UITableView()
        
        control.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: BTSafeAreaBottom + 50 , right: 0)
        
        control.delegate = self
        
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        control.dataSource = self
        
        control.register(cellWithClass: UITableViewCell.self)
        control.register(cellWithClass: PecGroupCommentsPlaceHolderCell.self)
        control.register(cellWithClass: ST_PecGroupCommentsCell.self)
        
        
        control.register(headerFooterViewClassWith: ST_PairsCenterCornerSectionHeaderView.self)
        control.register(headerFooterViewClassWith: ST_PairsCenterCornerSectionFooterView.self)
        
        
        control.separatorStyle = .none
        
        control.backgroundColor = Color.init(hex: 0xACB4C0)
        
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        
        control.tableHeaderView = self.headerView
        control.tableFooterView = self.footerView
        
        return control
    }()
    
    //    MARK: - header Properties
    lazy var headerView:ST_PeculiarityGroupHeaderView = {
        
        let control = ST_PeculiarityGroupHeaderView(frame: CGRect.init(x: 0, y: 0, width: ScreenWidth, height: header_height))
        
        control.phDelegate = self
        
        control.create_play_view()
        
        return control
    }()
    
    fileprivate lazy var footerView:ST_PeculiarityGroupFooterView = {
        
        let control = ST_PeculiarityGroupFooterView(frame: CGRect.init(x: 0, y: 0, width: ScreenWidth, height: 0))
//        control.isHidden = true
        return control
    }()
    
    
    fileprivate lazy var bottom_input_action_view:ST_PecGroupBottomView = {
       let control = ST_PecGroupBottomView()
        control.beginInput = {[weak self] in
            self?.comment_input_bar.startEdit()
        }
        return control
    }()
    
    fileprivate lazy var comment_input_bar:ST_CommentInputBar = {
       let control = ST_CommentInputBar()
        control.endEditClosure = {[weak self] str,replyId,commentId in
            self?.end_edit_comment_handle()
            self?.send_message_handle(comment: str, replyUserId: replyId, commentId: commentId)
        }
        control.keyBroadHiddenClosure = {[weak self]  in
            self?.hidden_mask_view(hidden: true)
        }
        control.keyBroadShowClosure = {[weak self]  in
            self?.hidden_mask_view(hidden: false)
        }
        
        return control
    }()
    
    
    
    fileprivate lazy var bottom_button_effect_view:ST_FWGradientView = {
       let control = ST_FWGradientView()
        control.isUserInteractionEnabled = false
        
        if iPhoneXSeries{
            control.model = ST_FWGradientViewModel.init(locations: [0,0.7,1], colors: [UIColor.init(white: 1, alpha: 0),UIColor.init(white: 1, alpha: 0.85),UIColor.init(white: 1, alpha: 1)], startPoint: CGPoint.init(x: 0, y: 0), endPoint: CGPoint.init(x: 0, y: 1))
        }else{
            control.model = ST_FWGradientViewModel.init(locations: [0,0.7,1], colors: [UIColor.init(white: 1, alpha: 0),UIColor.init(white: 1, alpha: 0.85),UIColor.init(white: 1, alpha: 1)], startPoint: CGPoint.init(x: 0, y: 0), endPoint: CGPoint.init(x: 0, y: 1))
        }
        
        return control
    }()
    
    fileprivate lazy var accost_btn:UIControl = {
        let control = UIControl()
        
        let gradientBackView = ST_FWGradientView()
        gradientBackView.isUserInteractionEnabled = false
        gradientBackView.model = ST_FWGradientViewModel.init(locations: [0,1], colors: [UIColor.init(hex: 0xFFDE11)!,UIColor.init(hex: 0xF8BC00)!], startPoint: CGPoint.init(x: 0, y: 0), endPoint: CGPoint.init(x: 0, y: 1))
        control.addSubview(gradientBackView)
        gradientBackView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        let imgView = UIImageView()
        imgView.image = ST_ImageUtils.imageName("accost189232")
        control.addSubview(imgView)
        imgView.snp.makeConstraints { (make) in
            make.width.height.equalTo(24)
            make.centerY.equalToSuperview()
            make.centerX.equalToSuperview().offset(-12-5)
        }
        
        
        let label = UILabel()
        control.addSubview(label)
        label.text = "搭讪"
        label.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)
        label.textColor = .white
        label.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.centerX.equalToSuperview().offset(12+5)
        }
        
        control.cornerRadius = 22
        
        control.addTarget(self, action: #selector(accost_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    
    fileprivate lazy var chat_btn:ST_VerticalButton = {
        let control = ST_VerticalButton()
        control.setImageForAllStates(ST_ImageUtils.imageName("chatcopy034034")!)
        control.setTitleForAllStates("私聊".withAttributes([Attribute.font(UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)),.textColor(UIColor.init(hex: 0x333333)!)]))
        control.title_bottom_offset = 0
        control.image_view_edges = UIEdgeInsets.init(top: 0, left: 13, bottom: 20, right: 13)
        control.addTarget(self, action: #selector(chat_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var another_like_btn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImageForAllStates(ST_ImageUtils.imageName("个人中心_center_icon")!)
        control.addTarget(self, action: #selector(send_like_handle(sender:)), for: UIControl.Event.touchUpInside)
        return control
    }()

    
    fileprivate lazy var like_btn:ST_VerticalButton = {
        let control = ST_VerticalButton()
        control.setImageForAllStates(ST_ImageUtils.imageName("likeGold")!)
        control.setTitleForAllStates("喜欢".withAttributes([Attribute.font(UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)),.textColor(UIColor.init(hex: 0x333333)!)]))
        control.title_bottom_offset = 0
        control.image_view_edges = UIEdgeInsets.init(top: 0, left: 13, bottom: 20, right: 13)
        control.addTarget(self, action: #selector(send_like_handle(sender:)), for: UIControl.Event.touchUpInside)
        control.alpha = 0
        return control
    }()
    
    fileprivate lazy var gift_btn:ST_VerticalButton = {
        let control = ST_VerticalButton()
        control.setImageForAllStates(ST_ImageUtils.imageName("chat_gift_icon")!)
        control.setTitleForAllStates("礼物".withAttributes([Attribute.font(UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)),.textColor(UIColor.init(hex: 0x333333)!)]))
        control.title_bottom_offset = 0
        control.image_view_edges = UIEdgeInsets.init(top: 0, left: 13, bottom: 20, right: 13)
        control.addTarget(self, action: #selector(show_goods_handle), for: UIControl.Event.touchUpInside)
        control.alpha = 0
        return control
    }()
    
    
    fileprivate lazy var magic_btn:ST_VerticalButton = {
        let control = ST_VerticalButton()
        control.setImageForAllStates(ST_ImageUtils.imageName("magicGold")!)
        control.setTitleForAllStates("立即匹配".withAttributes([Attribute.font(UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)),.textColor(UIColor.init(hex: 0x333333)!)]))
        control.title_bottom_offset = 0
        control.image_view_edges = UIEdgeInsets.init(top: 0, left: 13, bottom: 20, right: 13)
        control.addTarget(self, action: #selector(open_magic_tools_handle(sender:)), for: UIControl.Event.touchUpInside)
        control.alpha = 0
        return control
    }()
    
    
//    MARK: - New Like Bottom Btns
    @objc func refresh_love_botton(){
        
        
        if self.headerModel.is_friends{
            
            gift_btn.alpha = 1
            like_btn.alpha = 0
            magic_btn.alpha = 0
            
        }else if self.headerModel.is_attention{
            
            magic_btn.alpha = 0
            like_btn.alpha = 0
            gift_btn.alpha = 1
            
        }else{
            
            like_btn.alpha = 1
            magic_btn.alpha = 0
            gift_btn.alpha = 0
        }
        
    }
    
    func layout_operation_btns(){
        
        if self.accid == Defaults[.currentUserID]{
            return
        }
        
        view.addSubview(bottom_button_effect_view)
        bottom_button_effect_view.snp.makeConstraints { (make) in
            make.bottom.left.right.equalToSuperview()
            make.height.equalTo(174-34+BTSafeAreaBottom)
        }
        
        view.addSubview(accost_btn)
        accost_btn.snp.makeConstraints { (make) in
            make.bottom.equalTo(bottom_button_effect_view).offset(-10-BTSafeAreaBottom)
            make.height.equalTo(44)
            make.width.equalTo(TIANCompatibleValue(value: 237))
            make.left.equalToSuperview().offset(15)
        }
        
        view.addSubview(magic_btn)
        magic_btn.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-12)
            make.width.equalTo(50)
            make.height.centerY.equalTo(accost_btn)
        }
        
        view.addSubview(like_btn)
        like_btn.snp.makeConstraints { (make) in
            make.edges.equalTo(magic_btn)
        }
        
        view.addSubview(gift_btn)
        gift_btn.snp.makeConstraints { (make) in
            make.edges.equalTo(magic_btn)
        }
        
        view.addSubview(chat_btn)
        chat_btn.snp.makeConstraints { (make) in
            make.height.centerY.width.equalTo(magic_btn)
            make.right.equalTo(magic_btn.snp.left).offset(0)
        }
        
        refresh_love_botton()
        
    }
    
    @objc func accost_handle(){
        
        
        if BTVerticalAlertViewController.toastBindPhoneRequireAlert(fromController: self) {
            return
        }
        
        self.accost_btn.isUserInteractionEnabled = false
        
        main_thread_execute(afterDelay: 1.5) {
            self.accost_btn.isUserInteractionEnabled = true
        }
        
        
        ST_TianAccostManager.shared.accost(idSet: [self.accid], viewController: self,success:  { (json) in
            
            
            
            self.toast(text: "搭讪成功")
            
            self.accost_btn.isSelected = true
        })
        
    }
    
    @objc func chat_handle(){
        
        let m = self.headerModel
        
        
        
        BINP.update_base_info(remoteInfo: ST_BTUserInfoFromRemote.init(accid: m.accid, avatar: m.avatar, userName: m.nickname))
        
        push_to_chat_controller(info: ST_ChatInfoStruct.init(sessionId: m.accid, title: m.nickname, source: "个人特质页"), navigationController: nil)
        
        
    }
    
    
    
    @objc fileprivate func open_magic_tools_handle(sender:UIControl){
        
      
        let vc = ST_SendAirshipViewController()
        
        vc.overCurrentContext = true
     
        vc.send_closure = {[weak self] m in
            self?.send_air_ship(model: m)
        }
        
        GlobalPresent(toController: vc)
        
    }
    
    @objc fileprivate func send_like_handle(sender:UIControl){
     
        
        if BTVerticalAlertViewController.toastBindPhoneRequireAlert(fromController: self) {
            return
        }
        
        push_to_remote_like_action(id: nil)
        
    }
    
    
    
    @objc func show_goods_handle(){
        
        let giftAlert = ST_GiftViewController()
        
        giftAlert.overCurrentContext = true
        
        giftAlert.over_current_context_alpha = "0.4"
        
        giftAlert.userId = self.accid
      
        if let user = BINP.fetch_nickname_with_avatar(userId: self.accid){
        
            giftAlert.avatar = user.avatar
        }
        
        
        GlobalPresent(toController: giftAlert)
        
    }
    
    
    
    fileprivate func send_air_ship(model:ST_ChooseAirshipCellModel){
        
        
        let vc = ST_PairsPropBrowserController()
                    
        vc.overCurrentContext = true
        
        vc.animationIndex = model.id
        
        vc.play_completion_closure = { [weak self] in
            
            self?.push_to_remote_like_action(id: model.id.string)
            
        }
        
        GlobalPresent(toController: vc, animated: false)
        
    }
    
    
    fileprivate func push_to_remote_like_action(id:String? = nil){
        
        
        self.like_btn.isUserInteractionEnabled = false
        
        let info = ST_MatchUserInfo(accid: self.accid, avatar: self.headerModel.avatar, nickname: self.headerModel.nickname)
        
        PairsLikeAction(info: info, likeAction: true, fromVC: self,propId:id) { (code, err , matched) in
            
            self.like_btn.isUserInteractionEnabled = true
            
            if code == 1{
                
                matched?()
                
                self.headerModel.is_attention = true
          
                self.layout_operation_btns()
                
            }else {
                
                if let e = err{ self.toast(text: e) }
                
            }
        
        }
        
        
    }
    
    
    
    fileprivate lazy var comment_input_mask_view:UIView = {
       let control = UIView()
        control.alpha = 0
        control.backgroundColor = UIColor.init(white: 0, alpha: 0.3)
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(end_edit_comment_handle))
        control.addGestureRecognizer(tap)
        return control
    }()
    
    @objc fileprivate func end_edit_comment_handle(){
        
        comment_input_bar.endEditing(true)
        
        
    }
    
    
    func send_message_handle(comment:String,replyUserId:String?,commentId:String?){
        
        //        只能发表情，但是没有检测到表情
        if self.commentsViewModel.type == 2 && comment.containEmoji == false{
            
            self.toast(text: "该特质只支持emoji评论")
            
            return
        }
        
        var param = ["target_accid":self.accid,"feature_id":self.peculiarity_id,"group_id":self.groupId,"type":self.commentsViewModel.type,"comment":comment] as [String : Any]
        
        if let id = commentId{
            param.updateValue(id, forKey: "target_comment_id")
        }
        if let id = replyUserId{
            param.updateValue(id, forKey: "target_member_id")
        }
        
        if let id = replyUserId{
        
           param.updateValue(id, forKey: "target_member_id")
         
       //            收到的评论页｜个人特质页
                   
           ST_BTGlobalDataCenter.shared.reply_peculiarity_comment_event(peculiarity_id: self.groupId, reply_user_id: id,source: "个人特质页", is_own_peculiarity: self.accid == Defaults[.currentUserID])
           
       }else{
           
           ST_BTGlobalDataCenter.shared.commentPeculiarityEvent(peculiarity_id: self.groupId, commented_user_id: self.accid)
           
       }
    
        if BTVerticalAlertViewController.toastBindPhoneRequireAlert(fromController: self) {
                return
            }
        
        if restrictFemaleFace(){
            return
        }
        
        if ST_BTUserInfoManager.shared.confined_to_ticket(){
                
                let vc = ST_TicketViewController()
                
                vc.from = .mainIndexConfined
                
                GlobalPresent(toController: vc)
                
                return
            }
        
        JVrequest(PH.sendCommentApi,parameters: param, success: { (json) in
            
//            self.currentPage = 0
//
//            self.request_data()
            
            self.fetch_remote_data_set()
            
        }) { (code, err) in
            self.toast(text: err)
        }
        
    }
    
    func hidden_mask_view(hidden:Bool){

        UIView.animate(withDuration: 0.25, animations: {
            
            self.comment_input_mask_view.alpha = hidden ? 0 : 1
            
        }) { (f) in
            
        }
        
    }
    
    var header_height = 100.cgFloat{
        didSet{
            
            self.headerView.frame = CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: ScreenWidth, height: header_height))
            
            let pairsheaderHeight = header_height - self.headerModel.frameModel.headerExtensionHeight
            
            self.headerView.pairsHeader?.frame = CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: ScreenWidth, height: pairsheaderHeight))
            
            self.tableView.tableHeaderView = self.headerView
            
            
            print("Bug 问题1：",self.header_height)
            
        }
    }
    
     
}
//MARK: - Event
extension ST_PeculiarityGroupViewController{
    
    @objc func back_handle(){
        
        headerView.isUserInteractionEnabled = false
        
        
        
        guard let nav = self.navigationController, let first = nav.viewControllers.first,first is ST_PeculiarityGroupViewController && first != self else {
            
            goback_previous_controller()
            
            return
        }
        
        nav.transitioningDelegate = nil
        
        nav.dismiss(animated: true) {
            
        }
        
        
    }
    
    
    
    
    @objc func ban_current_user_handle(){
        
        
        BAN_SOMEBODY_HANDLE(userId: self.accid, close_view: true, hud_controller: self)
        
    }
    
    /**
     屏蔽点击事件
     */
    func shield_click_on_loading(isShield:Bool){
        
        self.footerView.isUserInteractionEnabled = !isShield
        
        self.headerView.isUserInteractionEnabled = !isShield
        
        self.tableView.visibleCells.forEach { (itemCell) in
            itemCell.isUserInteractionEnabled = !isShield
        }
        
    }
    
  
    
    @objc func edit_my_info_handle(){
        
        let editVC = ST_EditMyInfoViewController()
        
        self.navigationController?.pushViewController(editVC, animated: true)
        
    }
    
    
    
    
   
    
    
    @objc func actions_handle(){
        
        
        let vc = ST_BTSheetActionController.init(title: nil, message: nil)
        
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium),.foregroundColor: UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)]
        
        
        if self.accid != Defaults[DefaultsKeys.currentUserID]{
            
            if ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == .male || Defaults[.isPanda] {
            
            let str2 = NSMutableAttributedString.init(string: "拉黑")
            
            str2.addAttributes(attr, range: NSRange(location: 0, length: str2.length))
            
            vc.addAction(ST_BTAlertAction.init(title: str2, handler: {[weak self] (action) in
                    
                guard let strongSelf = self else{return}
                
                strongSelf.ban_current_user_handle()
            }))
                
            }
            
            let str3 = NSMutableAttributedString.init(string: "举报")
            
            str3.addAttributes(attr, range: NSRange(location: 0, length: str3.length))
            
            vc.addAction(ST_BTAlertAction.init(title: str3, handler: {[weak self] (action) in
               
                
                guard let strongSelf = self else{return}
                
                let vc = ST_ReportPersonController()
                vc.userId = strongSelf.accid
                let nav = UINavigationController.create_hiding_bar_navigation_controller(rootViewController: vc)
                GlobalPresent(toController: nav)
                
            }))
            
        }else{
            
            
               let str4 = NSMutableAttributedString.init(string: "删除")
               
               str4.addAttributes(attr, range: NSRange(location: 0, length: str4.length))
               
               vc.addAction(ST_BTAlertAction.init(title: str4, handler: {[weak self] (action) in
                   
                   self?.tipsAction()
                   
               }))
            
            
        }
        
        
        
       
        
        vc.show()
        
        
        
    }
    
    
    @objc func tipsAction(){
        
        PlayFeedBack()
        
        let attrString = NSMutableAttributedString(string: "确认要删除此特质吗？")
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.medium),.foregroundColor: UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)]
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        
        let messageAttrString = NSMutableAttributedString(string: "删除后点赞和评论会被清空")
        
        let attr2: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14),.foregroundColor: UIColor(red: 0.38, green: 0.4, blue: 0.44, alpha: 1)]
        
        messageAttrString.addAttributes(attr2, range: NSRange(location: 0, length: messageAttrString.length))
        
        let alert = ST_BTAlertViewController.init(title: attrString, message: messageAttrString, imageName: "首页_icon_提示", confirmText: " 确定删除", cancelText: "再想想看")
        
        alert.overCurrentContext = true
        
        alert.over_current_context_alpha = "0.4"
        
        alert.confirm_closure = {[weak self] in
            
            self?.delete_current_group_handle()
            
        }
        
        GlobalPresent(toController: alert, animated: false)
        
    }
    
    fileprivate func delete_current_group_handle()  {
        
        
        JVrequest(PH.delGroupContentApi,parameters:  ["feature_id":self.peculiarity_id,"group_id":self.groupId] ,success: { (json) in
            
            NotificationCenter.default.post(name: Notification.Name.my_pairs_user_info_updated, object: nil)
            
            self.toast(text: "删除成功")
            
            main_thread_execute(afterDelay: 1.5) {
                self.dismiss(animated: false, completion: nil)
            }
            
        }) { (code, err) in
            
            self.toast(text: err)
        }
    }
    
}

//MARK: - Tools
extension ST_PeculiarityGroupViewController{
    
    
    
}

//MARK: - UITableViewDelegate
extension ST_PeculiarityGroupViewController:UITableViewDelegate,UITableViewDataSource{
    
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
        if self.commentsViewModel.list.count < 1{
                
            let cell = tableView.dequeueReusableCell(withClass: PecGroupCommentsPlaceHolderCell.self, for: indexPath)
            
            cell.beginInput = {[weak self] in
                self?.comment_input_bar.startEdit()
            }
            
            cell.tipsText(nickName:self.headerModel.nickname)
            
            cell.onlyInputEmoji = self.comment_input_bar.onlyInputEmoji
            
            return cell
            
        }else{
            
            let cell = tableView.dequeueReusableCell(withClass: ST_PecGroupCommentsCell.self, for: indexPath)
            
            cell.model = self.commentsViewModel
            
            cell.onlyInputEmoji = self.comment_input_bar.onlyInputEmoji
            
            cell.beginInput = {[weak self] in
                self?.comment_input_bar.startEdit()
            }
            
            cell.allCommentsClickClosure = {[weak self] model in
                
                let vc = ST_CommentListViewController()
                       
               vc.groupId = model.groupId
               
               vc.userId = model.userId
               
               vc.featureName = self?.headerView.model?.peculiarityName ?? ""
               
               vc.peculiarity_id = model.peculiarity_id
               
               vc.type = model.type
                       
               self?.navigationController?.pushViewController(vc)
                
            }
            
            cell.beginInputReplyClosure = {[weak self] id,commentId,nickName in
            
                self?.comment_input_bar.startEdit(replyUserId: id, commentId: commentId.string, nickName: nickName)
            }
            return cell
        }
            
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if self.commentsViewModel.list.count < 1{
            return 159 + 5
        }else{
            return self.commentsViewModel.cellHeight
        }
    }
    
    
    
    
    
    //    MARK: tableView click Event
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        
        
    }
    
    
}



//MARK: - Pairs Header Delegate

extension ST_PeculiarityGroupViewController:ST_PairsShareParticularViewDelegate{
    
    func PHScrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
    }
    
    
    func PHScrollViewDidScroll(_ scrollView: UIScrollView, viewHeight: CGFloat) {
        
        self.header_height = viewHeight + self.headerModel.frameModel.headerExtensionHeight
        
    }
    
    
}



